extends CharacterBody2D
class_name Box

var getting_force: bool = true
var cached_velocity: Vector2

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity.y += Globals.gravity * delta
	
	#move_and_slide because internally changes velocity
	cached_velocity = velocity
	
	move_and_slide()
	
	getting_force = false
	
	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		_process_collision(collision)

	#stop any horizontal movement if box isn't controlled/pushed by player
	if not getting_force:
		velocity.x = 0
	
func _process_collision(collision: KinematicCollision2D) -> void:
	var collider = collision.get_collider()
	var normal = collision.get_normal()
	
	if collider is Box:
		#Check correct sides
		if not (normal == Vector2.LEFT or normal == Vector2.RIGHT):
			return

		#Not to push if the boxes collide only with corners
		if abs(collider.position.y - position.y) > Globals.tile_size/2.0:
			return

		#Push box only if it has the same direction
		#Prevents box sticking to another box
		if (collider.velocity.x <= 0 and cached_velocity.x < 0) or \
		(collider.velocity.x >= 0 and cached_velocity.x > 0):
			var tmp = (collider.velocity.x + cached_velocity.x) / 2.0
			collider.velocity.x = tmp
			velocity.x = tmp
			collider.getting_force=true
